#include <string.h>
#include <time.h>
#include <unistd.h>

#include <libxml/tree.h>
#include <xmlsec/xmltree.h>

#include "mcx.h"

GHashTable *mcx_drawdown(xmlSecKeyPtr key, xmlDocPtr authority, char *currency, char *amount) {
  xmlDocPtr drawdown, response;

  drawdown = mcx_drawdown_request(key, authority, currency, amount);
  if(mcx_debug_get())
    xmlDocDump(stderr, drawdown);
  response = mcx_send("DrawdownService", drawdown);
  if(mcx_debug_get())
    xmlDocDump(stderr, response);
  return mcx_balanceStatus_parse(response);
}

xmlNodePtr mcx_amount(xmlDocPtr doc, xmlNsPtr *ns, char *currency, char *amount) {
  xmlNsPtr mcx;
  xmlNodePtr ret;
  
  if(!ns)
    ns = &mcx;
  if(!*ns)
    *ns = xmlNewNs(xmlDocGetRootElement(doc), ns_mcx, "mcx");

  ret = xmlNewDocNode(doc, *ns, "amount", amount);
  if(!ret)
    return NULL;
  
  xmlSetProp(ret, "currency", currency);
  return ret;
}

xmlDocPtr mcx_drawdown_request(xmlSecKeyPtr key, xmlDocPtr authority,
				 char *currency, char *amount) {
  xmlDocPtr drawdown;
  xmlNsPtr mcx = NULL;
  xmlNodePtr root, e;

  if(!key)
    return NULL;

  drawdown = mcx_doc_new(ns_mcxws, "mcxws", "drawdown", NULL, &root);
  if(!drawdown)
    return NULL;

  e = mcx_amount(drawdown, &mcx, currency, amount);
  if(!e)
    return NULL;
  xmlAddChild(root, e);
  xmlAddChild(root, xmlDocCopyNode(xmlDocGetRootElement(authority), drawdown, 1));
  e = mcx_validityInterval_offset(drawdown, &mcx, 0, 7 * 86400);
  if(!e)
    return NULL;
  xmlAddChild(root, e);
  e = mcx_sign(root, key);
  if(!e)
    return NULL;

  return drawdown;
}
